﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcMusicStore.Models;
using System.Web.Mvc;

namespace MvcMusicStore.Models
{
    public class ShoppingCart
    {
        //实例化MusicStoreEntities
        MusicStoreEntities db = new MusicStoreEntities();
        //购物车v标示
        string ShoppingCartId { set; get; }
        public const string CartSessionKey = "CartId";
        
        //返回用户的session名称或者缓存ID，即购无车标示
        public string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] = context.User.Identity.Name;

                }
                else
                {
                    Guid tempCartId = Guid.NewGuid();
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            
            }
            return context.Session[CartSessionKey].ToString();
        }
        public static ShoppingCart GetCart(HttpContextBase context)
        {
            var cart = new ShoppingCart();
            cart.ShoppingCartId = cart.GetCartId(context);
            return cart;
        }
        public static ShoppingCart GetCart(Controller controller)
        {
            return GetCart(controller.HttpContext);
        
        }

        public void AddCart(Album album)
        {
            var cartItem = db.Carts.SingleOrDefault(c=>c.CartId==ShoppingCartId&&c.AlbumId==album.AlbumId);
            if (cartItem == null)
            {
                cartItem = new Cart
                {

                    AlbumId = album.AlbumId,
                    CartId = ShoppingCartId,
                    Count = 1,
                    DateCreated = DateTime.Now
                };
                db.Carts.Add(cartItem);
            }
            else
            {
                cartItem.Count++;
            }
            db.SaveChanges();
        }

        public int RemoveFromCart(int id)
        {
            var cartItem = db.Carts.Single(c=>c.CartId==ShoppingCartId&&c.RecordId==id);
            int itemCount = 0;
            if (cartItem != null)
            {
                if (cartItem.Count > 1)
                {
                    cartItem.Count--;
                    itemCount = cartItem.Count;
                }
                else
                {
                    db.Carts.Remove(cartItem);
                }
                db.SaveChanges();
            }
            return itemCount;
        }
        public void EmptyCart()
        {
            var cartItems = db.Carts.Where(c=>c.CartId==ShoppingCartId);
            foreach (var cartItem in cartItems)
            {
                db.Carts.Remove(cartItem);
            }
            db.SaveChanges();
        
        }

        public List<Cart> GetCartItems()
        {
            return db.Carts.Where(c=>c.CartId==ShoppingCartId).ToList();
        }


        public int GetCount()
        {
            int? count = (from c in db.Carts
                         where c.CartId == ShoppingCartId
                         select (int)c.Count).Sum();
            return count??0;
        
        }
        public decimal GetTotal()
        {

            decimal? total = (from c in db.Carts
                              where c.CartId == ShoppingCartId
                              select (int?)c.Count * c.Album.Price
                                ).Sum();
            return total??decimal.Zero;
        }
        public int CreateOrder(Order order)
        {
            decimal orderTotal = 0;
            var cartItems = GetCartItems();
            foreach (var item in cartItems)
            {
                var orderDetail = new OrderDetail { 
                AlbumId=item.AlbumId,
                OrderId=order.OrderId,
                UnitPrice=item.Album.Price,
                Quantity=item.Count
                };
                orderTotal+=(item.Count*item.Album.Price);
                db.OrderDetails.Add(orderDetail);
            }
            order.Total = orderTotal;
            db.SaveChanges();
            EmptyCart();
            return order.OrderId;
        }

        public void MigrateCart(string userName)
        {
            var items = db.Carts.Where(c=>c.CartId==ShoppingCartId);
            foreach (Cart item in items)
            {
                item.CartId = userName;
            }
            db.SaveChanges();
        }

    }
}